import axios from 'axios'
import qs from 'qs'
import  md5 from 'js-md5'
import { paseTime } from './'
import { Toast } from 'vant'

const service = axios.create({
    baseURL: import.meta.env.VITE_API,
    timeout: 5000,
    transformRequest: data => qs.stringify(data)
})


// 请求拦截器
service.interceptors.request.use(config => {
    const params = {
        rayTimeStamp: paseTime(new Date()),
        raySignature: `wX9CBe999999${md5(md5(`${paseTime(new Date())}1231212XXXXDDDDEEEFx2312121212`))}`
    }
    if (config.method === 'post') {
        config.data = {
            ...config.data,
            ...params
        }
    } else if (config.method === 'get') {
        config.params = {
            ...config.params,
            ...params
        }
    }
    return config
})


// 返回结果拦截器
service.interceptors.response.use(response => {
    const result = response.data
    if (result.code !== 200) {
        Toast({
            message: result.message,
            position: 'top'
        })
    }
    console.log(result)
     return result
}, error => { // 错误处理
    console.log(error)
    Toast({
        message: error.message,
        position: 'top'
    })
    return Promise.reject(error)
})

export default service
